package com.hk.Mgr.web.controller.safety;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.ConstantSafety;
import com.hk.commons.HqlFilter;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.Safety;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.vo.CheckInfo;
import com.hk.commons.vo.SafetyMsg;
import com.hk.commons.vo.SafetyVo;
import com.hk.service.ISafety;
import com.hk.service.sys.ISysUser;
import com.hk.service.sys.ISysUserRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lemon 用户实现类
 */
@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/safetyCtrl")
public class SafetyCtrl extends BaseCtrl {

	private Logger logger = LoggerFactory.getLogger(SafetyCtrl.class);


	@Autowired
	private ISafety  safetyService;

	@Autowired
	private ISysUserRoles roleService;

	@Autowired
	private ISysUser userService;

	/**
	 * 获取金账户回款短信验证码相关信息
	 * @param req
	 * @return
     */
	@ResponseBody
	@RequestMapping(value = "/getGoldAccountInfo", method = RequestMethod.POST)
	public ResponseBase<Map<String, Object>> getGoldAccountInfo(@RequestBody SafetyMsg req) {

		ResponseBase<Map<String, Object>> resp = new ResponseBase<Map<String, Object>>();

		logger.info("in getGoldAccountInfo");

		if(req == null || req.getUserId() == null){
			resp.setMsg("登录超时，请新登录");
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			return resp;
		}

		Long userId = req.getUserId();

		if(roleService.isSafety(userId) == false){
			resp.setMsg("您没有权限，请退出");
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			return resp;
		}

		try{

			Safety safety = safetyService.getByKey(ConstantSafety.SAFETY_PAY_BACK);

			if(safety == null){
				resp.setMsg("没有数据，请退出");
				resp.setResultCode(StatusCode.DATA_NOTEXISTS.key());
				return resp;
			}

			Map<String, Object > map = new HashMap<>();
			map.put("key", safety.getKeyName());
			map.put("field01", safety.getField01());
			map.put("field02", safety.getField02());
			map.put("field03", safety.getField03());
			map.put("field04", safety.getField04());
			map.put("desc", safety.getSafetyDesc());
			resp.setResult(map);
			resp.setResultCode(StatusCode.SUCCESS.key());
			return resp;
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
			return resp;
		}
	}

	/**
	 * 更新金账户回款短信验证码相关信息
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/updGoldAccountInfo", method = RequestMethod.POST)
	public ResponseBase<Boolean> updGoldAccountInfo(@RequestBody SafetyMsg req) {

		ResponseBase<Boolean> resp = new ResponseBase<Boolean>();

		logger.info("in updGoldAccountInfo");

		if(req == null || req.getUserId() == null
				|| StringHelper.isEmpty(req.getPayBackPhone01())
				|| StringHelper.isEmpty(req.getPayBackPhone02())
				|| StringHelper.isEmpty(req.getPayBackMail01())
				|| StringHelper.isEmpty(req.getPayBackMail02())){
			resp.setMsg("登录超时，请新登录");
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			return resp;
		}

		Long userId = req.getUserId();


		if(roleService.isSafety(userId) == false){
			resp.setMsg("您没有权限，请退出");
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
			return resp;
		}

		try{

			Safety safetyBefore = safetyService.getByKey(ConstantSafety.SAFETY_PAY_BACK);


			Safety safetyAfter = safetyService.getByKey(ConstantSafety.SAFETY_PAY_BACK);

			if(safetyAfter == null){
				resp.setMsg("没有数据，请退出");
				resp.setResultCode(StatusCode.DATA_NOTEXISTS.key());
				return resp;
			}

			safetyAfter.setField01(req.getPayBackPhone01().trim());
			safetyAfter.setField02(req.getPayBackPhone02().trim());
			safetyAfter.setField03(req.getPayBackMail01());
			safetyAfter.setField04(req.getPayBackMail02());

			safetyService.update(safetyAfter);

			safetyService.addPayBackLogRecord(userId, safetyBefore, safetyAfter);

			resp.setResult(true);
			resp.setResultCode(StatusCode.SUCCESS.key());
			return resp;
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
			return resp;
		}
	}

	/**
	 * 获取安全设置的列表
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getSafteList", method = RequestMethod.POST)
	public ResponseBase<List<Safety>> getSafteList(@RequestBody SafetyVo req){
		ResponseBase<List<Safety>> result = new ResponseBase<>();
		if(req.getActUserId() == null){
			result.setMsg("登录超时，请再次登录！");
			result.setResultCode(StatusCode.PARAM_ERROR.key());
			return result;
		}

		List<Safety> safetyList = new ArrayList<>();
		HqlFilter hqlFilter = new HqlFilter();

		hqlFilter.addSql(" where 1=1 ");
		try {
			if(req.getCurPage()>1000){
				Long size = safetyService.countByFilter(hqlFilter);
				result.setSize(size);
				result.setResult(safetyList);
			}else {
				safetyList = safetyService.findByFilter(hqlFilter,req.getCurPage(),req.getPageSize());
				if(safetyList == null || safetyList.size() == 0){
					result.setResultCode(StatusCode.DATA_NOTEXISTS.key());
					result.setMsg("数据不存在！");
					return result;
				}
				result.setSize(safetyList.size());
				result.setResult(safetyList);
				result.setResultCode(StatusCode.SUCCESS.key());

			}
		}catch (Exception e){
			logger.error(e.getMessage(), e);
			result.setMsg("操作异常，请重试");
			result.setResultCode(StatusCode.EXCEPTION.key());
		}
		return  result;
	}

	/**
	 * 更新安全验证信息
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateSafety", method = RequestMethod.POST)
	public ResponseBase<Safety> updateSafety(@RequestBody SafetyVo req){
		ResponseBase<Safety> result = new ResponseBase<>();
		if(req.getActUserId() == null){
			result.setMsg("登录超时，请再次登录！");
			result.setResultCode(StatusCode.PARAM_ERROR.key());
			return result;
		}

		if(roleService.isSafety(req.getActUserId()) == false){
			result.setMsg("您没有权限，请退出");
			result.setResultCode(StatusCode.PARAM_ERROR.key());
			return result;
		}
		try {
			Safety before = safetyService.getById(req.getId());

			Safety after = new Safety();
			after.setId(req.getId().intValue());
			after.setField01(req.getField01());
			after.setField02(req.getField02());
			after.setField03(req.getField03());
			after.setField04(req.getField04());
			after.setKeyName(req.getKeyName());
			after.setSafetyDesc(req.getSafetyDesc());

			safetyService.update(after);
			safetyService.addUpdateLog(req.getActUserId(),before,after);
			result.setResult(after);

		}catch (Exception e){
			logger.error(e.getMessage(), e);
			result.setMsg("操作异常，请重试");
			result.setResultCode(StatusCode.EXCEPTION.key());
			return result;
		}
		return result;
	}

	/**
	 * 发送销户短信验证码
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getCloseAccountCode", method = RequestMethod.GET)
	public ResponseBase<Boolean> getCloseAccountCode(Long userId){
		ResponseBase<Boolean> result = new ResponseBase<>();
		try {
			if(userId == null){
				result.setMsg("登录超时，请再次登录！");
				result.setResultCode(StatusCode.PARAM_ERROR.key());
				return result;
			}

			SysUser user = userService.findById(userId);
			if(user == null){
				result.setMsg("用户不存在，发送失败！");
				result.setResultCode(StatusCode.PARAM_ERROR.key());
				return result;
			}

			CheckInfo checkInfo = safetyService.sendCloseAccountCode(user.getRealName(),user.getName());

			if(checkInfo.getResult() == false) {
				result.setResultCode(StatusCode.ERROR.key());
				result.setMsg(checkInfo.getResultMsg());
				logger.info("销户，发送短信验证码失败! userId ={}", user.getId());
				return result;
			}

			result.setResult(true);
			result.setResultCode(StatusCode.SUCCESS.key());
			result.setMsg("发送短信验证码成功");
			return  result;
		}catch (Exception e){
			logger.error(e.getMessage(), e);
			result.setMsg("操作异常，请重试");
			result.setResultCode(StatusCode.EXCEPTION.key());
		}

        return result;

	}
}
